﻿@using WishlistUtilities;

@{
	PageData["Title"] = "Claim Item";

	var username = UrlData[0];
	var listSlug = UrlData[1];

	var db = Database.Open("wishlistdb");

	// lookup the id of the wishlist based on the username and list slug provided
	var wishlistId = ListLookupUtility.LookupListId(username, listSlug);

	if (wishlistId == -1) {
		Response.Redirect("~/Shared/Errors/Error");
	}

	if (IsPost) {
		var itemIdToClaim = Request["itemId"];

		if (itemIdToClaim.IsInt()) {
			// let's make sure the itemId exists
			var item = db.QuerySingle("SELECT * FROM Item WHERE Id = @0", itemIdToClaim);

			if (item != null) {
				try {
					db.Execute("UPDATE Item SET Claimed = 'true' WHERE Id = @0", itemIdToClaim);
				} catch (Exception) {
					Response.Redirect("~/Shared/Errors/Error");
				}
			} else {
				// it's also possible to get to this code if a user is claiming an item
				// just after it got deleted (race condition)
				Response.Redirect("~/Shared/Errors/Error");
			}
		} else {
			Response.Redirect("~/Shared/Errors/Error");
		}
	}


	var items = db.Query("SELECT * FROM Item WHERE ListId = @0", wishlistId);
	var wishlistName = db.QuerySingle("SELECT Name FROM List WHERE (Id = @0)", wishlistId).Name;

	<h1>@wishlistName</h1>
    
    var sortEnabled = Freemium.IsFeatureEnabledForCurrentUser("sort-lists");    
	WebGrid grid = new WebGrid(items, rowsPerPage: 5, canSort: sortEnabled);   

	@grid.GetHtml(
		columns: grid.Columns(
			grid.Column("Name", "Item"),
			grid.Column("Price", format: @<div>$@item.Price</div>),
			grid.Column("Link", format: @<a href="@item.Link">@item.Link</a>),
			grid.Column(columnName: "Claimed", header: "Item claimed?", format:
				@<text>
					@if (!@item.Claimed) {
						<form method="post" action="">
							<input name="itemId" type="hidden" value="@item.Id" />							
							<input type="submit" value="Claim item"/>
						</form>
					} else {
						@:Claimed
					}
				</text>
			)
		)
	)
}